
package View;


//Import packages
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.*;

/*
 * @author CCD gruppe 2
 */

public class CalendarFrame extends JFrame {

    static JLabel lblMonth;
    static JButton btnPrev, btnNext, okButton;
    static JTable tblCalendar;
    static JComboBox cmbYear;
    static Container pane;
    static DefaultTableModel mtblCalendar; //Table model
    static JScrollPane stblCalendar; //The scrollpane
    static JPanel pnlCalendar;
    static int realYear, realMonth, realDay, currentYear, currentMonth;
    private static int startOfMonth;
    static DecimalFormat dmf;
    static boolean clicked;

    static String stringDate;

    public CalendarFrame(){
        run();
    }

    public void run(){
        //Prepare frame
        setSize(330, 375); //Set size to 400x400 pixels
        setCenterPos(this);
        pane = getContentPane(); //Get content pane
        pane.setLayout(null); //Apply null layout

        //Create controls
        lblMonth = new JLabel("Januar");
        okButton = new JButton("År");
        cmbYear = new JComboBox();
        btnPrev = new JButton("<<");
        btnNext = new JButton(">>");
        dmf = new DecimalFormat("00");
        clicked = false;
        mtblCalendar = new DefaultTableModel() {

            public boolean isCellEditable(int rowIndex, int mColIndex) {
                return false;
            }
        };
        tblCalendar = new JTable(mtblCalendar);
        stblCalendar = new JScrollPane(tblCalendar);
        pnlCalendar = new JPanel(null);

        //Set border
        pnlCalendar.setBorder(BorderFactory.createTitledBorder("Kalender"));

        //Register action listeners
        btnPrev.addActionListener(new btnPrev_Action());
        btnNext.addActionListener(new btnNext_Action());
        cmbYear.addActionListener(new cmbYear_Action());

        //Add controls to pane
        pane.add(pnlCalendar);
        pnlCalendar.add(lblMonth);
        pnlCalendar.add(okButton);
        pnlCalendar.add(cmbYear);
        pnlCalendar.add(btnPrev);
        pnlCalendar.add(btnNext);
        pnlCalendar.add(stblCalendar);

        //Set bounds
        pnlCalendar.setBounds(0, 0, 320, 335);
        lblMonth.setBounds(160 - lblMonth.getPreferredSize().width / 2, 25, 100, 25);
        okButton.setBounds(10, 305, 80, 20);
        cmbYear.setBounds(215, 305, 100, 20);
        btnPrev.setBounds(10, 25, 50, 25);
        btnNext.setBounds(260, 25, 50, 25);
        stblCalendar.setBounds(10, 50, 300, 250);
        okButton.setText("Ok");

        setResizable(false);
        setVisible(false);

        //Get real month/year
        GregorianCalendar cal = new GregorianCalendar(); //Create calendar
        realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day
        realMonth = cal.get(GregorianCalendar.MONTH); //Get month
        realYear = cal.get(GregorianCalendar.YEAR); //Get year
        currentMonth = realMonth; //Match month and year
        currentYear = realYear;

        //Add headers
        String[] headers = {"Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"}; //All headers
        for (int i = 0; i < 7; i++) {
            mtblCalendar.addColumn(headers[i]);
        }

        tblCalendar.getParent().setBackground(tblCalendar.getBackground()); //Set background

        //No resize/reorder
        tblCalendar.getTableHeader().setResizingAllowed(false);
        tblCalendar.getTableHeader().setReorderingAllowed(false);

        //Single cell selection
        tblCalendar.setColumnSelectionAllowed(true);
        tblCalendar.setRowSelectionAllowed(true);
        tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        //Set row/column count
        tblCalendar.setRowHeight(38);
        mtblCalendar.setColumnCount(7);
        mtblCalendar.setRowCount(6);

        //Populate table
        for (int i = realYear - 100; i <= realYear + 100; i++) {
            cmbYear.addItem(String.valueOf(i));
        }

        //Refresh calendar
        refreshCalendar(realMonth, realYear); //Refresh calendar
        setVisible(false);
    }

    private static void refreshCalendar(int month, int year) {
        //Variables
        String[] months = {"Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"};
        int nod, som; //Number Of Days, Start Of Month

        //Allow/disallow buttons
        btnPrev.setEnabled(true);
        btnNext.setEnabled(true);
        if (month == 0 && year <= realYear - 10) {
            btnPrev.setEnabled(false);
        } //Too early
        if (month == 11 && year >= realYear + 100) {
            btnNext.setEnabled(false);
        } //Too late
        lblMonth.setText(months[month]); //Refresh the month label (at the top)
        lblMonth.setBounds(160 - lblMonth.getPreferredSize().width / 2, 25, 180, 25); //Re-align label with calendar
        cmbYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box

        //Clear table
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                mtblCalendar.setValueAt(null, i, j);
            }
        }

        //Get first day of month and number of days
        GregorianCalendar cal = new GregorianCalendar(year, month, 1);
        nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
        som = cal.get(GregorianCalendar.DAY_OF_WEEK);

        //Draw calendar
        for (int i = 1; i <= nod; i++) {
            int row = new Integer((i + som - 2) / 7);
            int column = (i + som - 2) % 7;
            mtblCalendar.setValueAt(i, row, column);
        }

        //Apply renderers
        tblCalendar.setDefaultRenderer(tblCalendar.getColumnClass(0), new tblCalendarRenderer());
    }

    static class tblCalendarRenderer extends DefaultTableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean focused, int row, int column) {
            super.getTableCellRendererComponent(table, value, selected, focused, row, column);
            if (column == 0 || column == 6) { //Week-end
                setBackground(new Color(255, 220, 220));
            } else { //Week
                setBackground(new Color(255, 255, 255));
            }
            if (value != null) {
                if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear) { //Today
                    stringDate = realYear + "-" + dmf.format(checkMonth(lblMonth.getText())) + "-" + dmf.format(Integer.parseInt(value.toString()));
                    clicked = true;
                    //lblYear.setText(stringDate);
                    setBackground(new Color(220, 220, 255));
                }
            }
            setBorder(null);
            setForeground(Color.black);
            if (selected == true && value !=null) {
                setBackground(new Color(220, 220, 0));
                stringDate = currentYear + "-" + dmf.format(checkMonth(lblMonth.getText())) + "-" + dmf.format(Integer.parseInt(value.toString()));
                //lblYear.setText(stringDate);
                clicked = true;

            }
            return this;
        }
    }

    private static int checkMonth(String month){
        int monthNumber = 0;
        if(month.equals("Januar")) monthNumber = 1;
        else if(month.equals("Februar")) monthNumber = 2;
        else if(month.equals("Mars")) monthNumber = 3;
        else if(month.equals("April")) monthNumber = 4;
        else if(month.equals("Mai")) monthNumber = 5;
        else if(month.equals("Juni")) monthNumber = 6;
        else if(month.equals("Juli")) monthNumber = 7;
        else if(month.equals("August")) monthNumber = 8;
        else if(month.equals("September")) monthNumber = 9;
        else if(month.equals("Oktober")) monthNumber = 10;
        else if(month.equals("November")) monthNumber = 11;
        else if(month.equals("Desember")) monthNumber = 12;
        return monthNumber;

    }


    static class btnPrev_Action implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (currentMonth == 0) { //Back one year
                currentMonth = 11;
                currentYear -= 1;
            } else { //Back one month
                currentMonth -= 1;
            }
            refreshCalendar(currentMonth, currentYear);
        }
    }

    static class btnNext_Action implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (currentMonth == 11) { //Foward one year
                currentMonth = 0;
                currentYear += 1;
            } else { //Foward one month
                currentMonth += 1;
            }
            refreshCalendar(currentMonth, currentYear);
        }
    }

    static class cmbYear_Action implements ActionListener {


        public void actionPerformed(ActionEvent e) {
            if (cmbYear.getSelectedItem() != null) {
                String b = cmbYear.getSelectedItem().toString();
                currentYear = Integer.parseInt(b);
                refreshCalendar(currentMonth, currentYear);
            }
        }
    }

    /*
     * Getters
     */

    public JButton getOkButton(){
        return okButton;
    }

    public String getSelectedDate(){
        if(stringDate.trim().equals(""))return "";
        return stringDate;
    }

    /**
     * A method that returns true if clicked
     * @return
     */
    public boolean isClicked(){
        return clicked;
    }

    private static void setCenterPos(JFrame frame){
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((screen.getWidth() - frame.getWidth()) / 2);
    int y = (int) ((screen.getHeight() - frame.getHeight()) / 2);
    frame.setLocation(x, y);
}
    }

